﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace MockingBird.Common.Infrastructure.Soap
{
    public class SoapHttpDispatcher
    {
        private HttpWebRequest httpRequest;
        private SoapRequest soapRequest;

        public SoapHttpDispatcher(SoapRequest request)
        {
            this.soapRequest = request;
        }

        public string Dispatch(string targetUrl)
        {
            SetupHttpRequest(targetUrl);
            return GetResponse();
        }

        private void SetupHttpRequest(string targetUrl)
        {
            Uri uri = new Uri(targetUrl);
            httpRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpRequest.Headers.Add("SOAPAction", soapRequest.Action);
            //use the default Get on the soapRequest to get UTF-8 encoded requests
            byte[] requestByteArray = soapRequest.Get();
            httpRequest.ContentType = "text/xml";
            httpRequest.Method = "POST";
            httpRequest.ContentLength = requestByteArray.Length;

            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(requestByteArray, 0, requestByteArray.Length);
            requestStream.Close();
        }

        private string GetResponse()
        {
            HttpWebResponse response;
            byte[] responseBytes;
            StreamReader responseReader;
            string strResponse;
            try
            {
                response = (HttpWebResponse)httpRequest.GetResponse();
                Stream responseStream = response.GetResponseStream();

                responseReader = new StreamReader(responseStream, Encoding.UTF8);
                responseBytes = Encoding.UTF8.GetBytes(responseReader.ReadToEnd());
                strResponse = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length);


            }
            catch (WebException webEx)
            {
                throw webEx;

            }
            return strResponse;



        }

    }
}
